﻿using System.Collections.Generic;
using System.Threading.Tasks;

namespace Puppy.Scheduler.Processors
{
    /// <summary>
    /// 广播处理器
    /// </summary>
    public abstract class BroadcastProcessor : ProcessorBase
    {
        /// <summary>
        /// 在所有节点广播执行前执行，只会在一台机器执行一次
        /// </summary>
        /// <param name="context">任务上下文</param>
        /// <returns></returns>
        public virtual Task<ProcessResult> PreProcessAsync(TaskContext context)
        {
            return Task.FromResult(new ProcessResult(true));
        }

        /// <summary>
        /// 在所有节点广播执行完成后执行，只会在一台机器执行一次
        /// </summary>
        /// <param name="context">任务上下文</param>
        /// <returns></returns>
        public virtual Task<ProcessResult> PostProcessAsync(TaskContext context, List<TaskResult> taskResults)
        {
            return Task.FromResult(DefaultResult(taskResults));
        }

        public static ProcessResult DefaultResult(List<TaskResult> taskResults)
        {
            long succeed = 0, failed = 0;
            foreach (var result in taskResults)
            {
                if (result.IsSuccess)
                    succeed++;
                else
                    failed++;
            }
            return new ProcessResult(failed == 0, $"succeed:{succeed}, failed:{failed}");
        }
    }
}
